package com.joolun.framework.interceptor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import com.joolun.common.core.domain.entity.SysUser;
import com.joolun.common.core.domain.model.LoginUser;
import com.joolun.common.corp.TenantContext;
import com.joolun.common.utils.SecurityUtils;
import com.joolun.system.service.ISysDeptService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson2.JSON;
import com.joolun.common.annotation.RepeatSubmit;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.utils.ServletUtils;

/**
 * 防止重复提交拦截器
 *
 * @author ruoyi
 */
@Component
public abstract class RepeatSubmitInterceptor implements HandlerInterceptor
{
    @Autowired
    private ISysDeptService deptService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        String requestURI = request.getRequestURI();
        // 放行列表（与Security配置保持一致）
        List<String> permitUrls = Arrays.asList(
                "/login", "/register", "/captchaImage", "/zb/room/zbUrl",//"/zb/video/upload/url",
                "/promotion/website/delivery/plan", "/weixin/portal/**","/wxuser/loginByMp",
                "/weixin/api/**", "/qywx/portal/**", "/joolun-wiki/**",
                "/scrm/plan/m/**","/scrm/plan/updateMobileStatis/**","/scrm/plan/getWxContactCode",
                "/auth/forword","/auth/loginByCode","/auth/createJsapiSignature/**",
                "/common/sendSms","/common/oss/callback","/common/oss/stsToken",
                "/ipaynow/back","/pay/now/**"
        );

        // 判断请求是否在放行列表中
        if (permitUrls.stream().anyMatch(url -> matchUrl(url, requestURI))) {
            return true; // 直接放行，不执行后续逻辑
        }

        if (handler instanceof HandlerMethod)
        {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            try {
                // 获取并设置主体ID
                String tenantId = null;
                HttpSession session = request.getSession(false);
                if (session != null) {
                    tenantId = (String) session.getAttribute("corp_id");
                } else {
                    // session超时，从Security上下文中获取
                    LoginUser loginUser = SecurityUtils.getLoginUser();
                    tenantId = deptService.getDeptByCorpId(loginUser);
                    if (tenantId != null) {
                        // 刷新session
                        request.getSession().setAttribute("corp_id", tenantId);
                    }
                }
                if (tenantId != null) {
                    TenantContext.setTenantId(tenantId);
                } else {
                    // 处理租户ID为空的情况（可选）
                    AjaxResult ajaxResult = AjaxResult.error("未获取到主体信息");
                    ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                    return false;
                }
            } catch (Exception e) {
                // 处理异常（如用户未登录）
                AjaxResult ajaxResult = AjaxResult.error("权限验证失败：" + e.getMessage());
                ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                return false;
            }
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null)
            {
                // 检查重复提交
                if (this.isRepeatSubmit(request, annotation)) {
                    AjaxResult ajaxResult = AjaxResult.error(annotation.message());
                    ServletUtils.renderString(response, JSON.toJSONString(ajaxResult));
                    return false;
                }

            }
            // 拦截获取主体ID
//            HttpSession session = request.getSession(false);
//            if (session != null) {
//                String tenantId = (String) session.getAttribute("corp_id");
//                if (tenantId != null) {
//                    TenantContext.setTenantId(tenantId);
//                }
//            }else{
//                // session超时，重新获取
//                LoginUser loginUser = SecurityUtils.getLoginUser();
//                // 获取当前登录账号的所属主体id
//                String tenantId = deptService.getDeptByCorpId(loginUser);
//                if (tenantId != null) {
//                    // 刷新session
//                    request.getSession().setAttribute("corp_id", tenantId);
//                    TenantContext.setTenantId(tenantId);
//                }
//            }





            return true;
        }
        else
        {
            return true;
        }
    }
    // 简单的URL匹配方法（支持**通配符）
    private boolean matchUrl(String pattern, String url) {
        if (pattern.contains("**")) {
            String regex = pattern.replace("**", ".*");
            return url.matches(regex);
        }
        System.out.println("url: ---------" + url);
        return url.startsWith(pattern);
    }
    /**
     * 验证是否重复提交由子类实现具体的防重复提交的规则
     *
     * @param request 请求信息
     * @param annotation 防重复注解参数
     * @return 结果
     * @throws Exception
     */
    public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation);
}
